#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import pymysql
import uuid
from datetime import datetime, timedelta, date
import time
def generate_token(length=21):
    # 生成多个UUID并拼接
    uuid_string = ''
    while len(uuid_string) < length:
        uuid_string += str(uuid.uuid4()).replace('-', '')
    return uuid_string[:length]

def stock_sk_share(param: str = "param"):
    token = generate_token()
    last_update_time = int((datetime.now() - timedelta(minutes=15)).replace(second=0, microsecond=0).timestamp())

    url = "https://www.zhitongcaijing.com/immediately/content-list.html?type="+param+"&roll=gt&token="+token+"&last_update_time="+str(last_update_time)+"&platform=web"

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
    }

    requests.get("https://www.zhitongcaijing.com/user/profile.html?token="+token+"&platform=web", headers=headers)
    print(url)

    # 尝试最多10次，每次间隔1秒
    for _ in range(10):
        try:
            r = requests.get(url, headers=headers, timeout=10)
            json_data = r.json()
            if json_data.get("status") == "success":
                return json_data
        except Exception as e:
            print(f"请求异常: {e}")

        time.sleep(2)  # 等待1秒后重试

    return {"status": "failed", "data": {}}

if __name__ == "__main__":
    param = "${param}"
    json_data = stock_sk_share(param)
    # 连接到MySQL数据库 - 使用pymysql方式
    cnx = pymysql.connect(
        user='dolphinadmin',
        password='XjYkRXwjmRRmMmXD',
        host='localhost',
        database='dolphinscheduler',
        charset='utf8mb4'
    )
    cursor = cnx.cursor()
    original_list = json_data['data']['list']
    for item in original_list:
        insert_query = "INSERT INTO bond_pull_board_data (stock,param,pull_date,response) VALUES (%s, %s, %s, %s);"
        create_time=  item.get('create_time', '')
        datetime_str = datetime.fromtimestamp(int(create_time)).strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute(insert_query, ('${stock}', param, datetime_str, item.get('content', '')))
    cnx.commit()
    cursor.close()
    cnx.close()
